import { ResidentModel } from '../models/resident.js';

export const ResidentController = {
  async getAllResidents(req, res) {
    try {
      const residents = await ResidentModel.getAllResidents();
      res.json(residents);
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch residents' });
    }
  },

  async getResidentById(req, res) {
    try {
      const resident = await ResidentModel.getResidentById(req.params.id);
      if (resident) {
        res.json(resident);
      } else {
        res.status(404).json({ error: 'Resident not found' });
      }
    } catch (error) {
      res.status(500).json({ error: 'Failed to fetch resident' });
    }
  },

  async createResident(req, res) {
    try {
      const id = await ResidentModel.createResident(req.body);
      res.status(201).json({ id, ...req.body });
    } catch (error) {
      res.status(500).json({ error: 'Failed to create resident' });
    }
  },

  async updateResident(req, res) {
    try {
      const success = await ResidentModel.updateResident(req.params.id, req.body);
      if (success) {
        res.json({ id: req.params.id, ...req.body });
      } else {
        res.status(404).json({ error: 'Resident not found' });
      }
    } catch (error) {
      res.status(500).json({ error: 'Failed to update resident' });
    }
  },

  async deleteResident(req, res) {
    try {
      const success = await ResidentModel.deleteResident(req.params.id);
      if (success) {
        res.status(204).send();
      } else {
        res.status(404).json({ error: 'Resident not found' });
      }
    } catch (error) {
      res.status(500).json({ error: 'Failed to delete resident' });
    }
  }
};